package com.chookss.tiku

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.chookss.R
import com.chookss.Urls
import com.chookss.tools.MyToast
import com.chookss.tools.Utils
import com.chookss.view.*
import com.chookss.view.listener.ShareDialogListener
import com.johnrambo.ktea.ktExtends.observe
import errorToast
import kotlinx.android.synthetic.main.activity_practice_test_base.*
import kotlinx.android.synthetic.main.activity_practice_test_base.subjectView
import kotlinx.android.synthetic.main.activity_practice_test_base.tvActivityTitle
import kotlinx.android.synthetic.main.view_subject.*
import successToast
import java.util.*

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/28
 * Note:
 */
class MyErrorSubjectActivity : BasePracticeTestActivity<MyErrorSubjectViewModel>() {
    lateinit var btnError: View
    var type: Int = 0 //0默认错题模式-1开启练习模式
    var subjectAllNums: Int = 0 //总错题数量
    var beitiType: Boolean = true  //是否背题模式    收藏和错题默认开启背题模式
    var typeAdapter: TitleAdapter? = null
    var subjectAdapter: TitleAdapter? = null
    var memoryAdapter: TitleAdapter? = null
    private val subjectList = ArrayList<HashMap<String, String>>()
    private val typeList = ArrayList<HashMap<String, String>>()
    private val memoryList = ArrayList<HashMap<String, String>>()
    var selectSubject = ArrayList<String>()
    var selectType = ArrayList<String>()
    var selectMemory = ArrayList<String>()
    var bottomListsDialog: BottomListsDialog? = null
    private val dialogList: ArrayList<String> = ArrayList()
    override fun createViewModel(): MyErrorSubjectViewModel {
        return ViewModelProviders.of(this).get(MyErrorSubjectViewModel::class.java).apply {
            memoryLvl = ""
            subjectTypeCode = ""
            sourceType = ""
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        tvActivityTitle.text = "错题本"
        subjectAllNums = intent.getIntExtra("subjectAllNums", 0)
        subjectView().showSubjectNext = 2
        tvTopBarRight.visibility = View.GONE
        ivSubjectShaixuan.visibility = View.VISIBLE
        ivTypeShaixuan.visibility = View.VISIBLE
        ivMemory.visibility = View.VISIBLE

        llFloatBtns.visibility = View.VISIBLE
        tvLianxi.visibility = View.VISIBLE
        tvDelete.visibility = View.VISIBLE
        tvCollect.visibility = View.VISIBLE
        tvMore.visibility = View.VISIBLE
        tvMore.setOnClickListener {
            if (Urls.antiShake.check()) {
                return@setOnClickListener
            }
            if (bottomListsDialog != null) {
                bottomListsDialog?.show()
            }
        }
        tvDelete.setOnClickListener { deleteErrorSubject() }
        tvLianxi.setOnClickListener {
            if (Urls.antiShake.check()) {
                return@setOnClickListener
            }
            if (type == 0) {
                LianxiDialog(this, type,
                    ShareDialogListener {
                        type = -1
                        tvLianxi.isSelected = true
                        tvActivityTitle.text = "错题练习"
                        subjectView().showSubjectNext = 1
                        beitiType = false
                        ivTypeShaixuan.visibility = View.GONE
                        isShowAnswer = false
                        subjectView().hiddeAnswerDetail()
                        MyToast.show("进入练习模式")
                        tvError.visibility = View.VISIBLE
                        tvShare.visibility = View.VISIBLE
                        tvDelete.visibility = View.GONE
                        tvMore.visibility = View.GONE
                    }).show()
            } else {
                LianxiDialog(this, type,
                    ShareDialogListener {
                        type = 0
                        tvLianxi.isSelected = false
                        tvActivityTitle.text = "错题本"
                        beitiType = true
                        MyToast.show("退出练习模式")
                        subjectView().showSubjectNext = 2
                        ivTypeShaixuan.visibility = View.VISIBLE
                        tvDelete.visibility = View.VISIBLE
                        tvMore.visibility = View.VISIBLE
                        tvError.visibility = View.GONE
                        tvShare.visibility = View.GONE
                        if (!isShowAnswer) {
                            getSubjectDetail();
                        }
                    }).show()
            }
        }
        dialogList.add("纠错")
        dialogList.add("分享")
        dialogList.add("取消")
        bottomListsDialog =
            BottomListsDialog(mContext!!, dialogList, object : SelectDialogListener {
                override fun onCancel() {}
                override fun onListItemClick(position: Int, list: List<String>) {
                    bottomListsDialog!!.setSelect(position)
                    if (position == 0 && subjectView != null) {
                        if (subjectView.subject != null) {
                            var subject = subjectView.subject!!
                            var intent = Intent(mContext, FeedbackActivity::class.java)
                            intent.putExtra("subjectCode", subject.subjectCode)
                            startActivity(intent)
                        }
                    } else if (position == 1) {
                        shareSubject()
                    }
                    bottomListsDialog!!.dismiss()
                }
            })
        tvSubjectNext.setOnClickListener {
            if (beitiType) {
                isShowAnswer = false
                gotoSubject(subjectIndex + 1)
            } else {
                if (isShowAnswer) {
                    isShowAnswer = false
                    gotoSubject(subjectIndex + 1)
                } else {
                    if (subjectView.myAnswers.size > 0) {
                        isShowAnswer = false
                        gotoSubject(subjectIndex + 1)
                    } else {
                        MyToast.show("请先答题，再提交")
                    }
                }

            }
        }
        initRvs()
    }

    fun getSubjectDetail() {
        if (subjectView != null) {
            if (subjectView.subject == null) {
                return
            }
            viewModel.getSubjectDetail(subjectView.subject!!)
                .observe(this, {
                    loadingProgress.dismiss()
                    if (it.error != null) {
                        errorToast(it.error.message ?: "")
                    } else {
                        if (subjectView.subject?.subjectTypeCode.equals("1004")) {
                            subjectView().updateMyAnswers(subjectView.subject?.optionLvlNo?.split("@#^"))
                        } else if (subjectView.subject?.subjectTypeCode.equals("1005")) {
                            var value: ArrayList<String> = ArrayList()
                            value.add(subjectView.subject?.optionLvlNo.toString())
                            subjectView().updateMyAnswers(value)
                        } else {
                            subjectView().updateMyAnswers(subjectView.subject?.optionLvlNo?.split(","))
                        }
                        subjectView.showRightAnswerInfo()
                        onAnswerSubmited(
                            subjectIndex,
                            subjectView.subject!!,
                            subjectView.myAnswers
                        )
                        isShowAnswer = true
                        subjectView.showAnswerDetail(it.data)
                    }
                })
        }
    }

    private fun initRvs() {
        rvSubject.setLayoutManager(
            LinearLayoutManager(
                mContext,
                LinearLayoutManager.VERTICAL,
                false
            )
        )
        rvSubject.addItemDecoration(
            RecycleViewDivider(
                this,
                LinearLayoutManager.HORIZONTAL,
                Utils.dip2px(this, 0.5f),
                resources.getColor(R.color.line_gray)
            )
        )
        rvType.setLayoutManager(LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false))
        rvType.addItemDecoration(
            RecycleViewDivider(
                this,
                LinearLayoutManager.HORIZONTAL,
                Utils.dip2px(this, 0.5f),
                resources.getColor(R.color.line_gray)
            )
        )
        rvMemory.setLayoutManager(
            LinearLayoutManager(
                mContext,
                LinearLayoutManager.VERTICAL,
                false
            )
        )
        rvMemory.addItemDecoration(
            RecycleViewDivider(
                this,
                LinearLayoutManager.HORIZONTAL,
                Utils.dip2px(this, 0.5f),
                resources.getColor(R.color.line_gray)
            )
        )
        val map: HashMap<String, String> = HashMap()
        map.put("title", "单选题")
        map.put("data", "1001")
        map.put("select", "false")
        subjectList.add(map)
        val map2: HashMap<String, String> = HashMap()
        map2.put("title", "多选题")
        map2.put("data", "1002")
        map2.put("select", "false")
        subjectList.add(map2)
        val map3: HashMap<String, String> = HashMap()
        map3.put("title", "判断题")
        map3.put("data", "1003")
        map3.put("select", "false")
        subjectList.add(map3)
        val map4: HashMap<String, String> = HashMap()
        map4.put("title", "填空题")
        map4.put("data", "1004")
        map4.put("select", "false")
        subjectList.add(map4)
        val map5: HashMap<String, String> = HashMap()
        map5.put("title", "问答题")
        map5.put("data", "1005")
        map5.put("select", "false")
        subjectList.add(map5)
        val typeMap: HashMap<String, String> = HashMap()
        typeMap.put("title", "全部")
        typeMap.put("data", "")
        typeMap.put("select", "false")
        typeList.add(typeMap)
        val typeMap2: HashMap<String, String> = HashMap()
        typeMap2.put("title", "智能练习")
        typeMap2.put("data", "1")
        typeMap2.put("select", "false")
        typeList.add(typeMap2)
        val typeMap3: HashMap<String, String> = HashMap()
        typeMap3.put("title", "专项练习")
        typeMap3.put("data", "2")
        typeMap3.put("select", "false")
        typeList.add(typeMap3)
        val typeMap4: HashMap<String, String> = HashMap()
        typeMap4.put("title", "模拟卷")
        typeMap4.put("data", "3")
        typeMap4.put("select", "false")
        typeList.add(typeMap4)
        val typeMap5: HashMap<String, String> = HashMap()
        typeMap5.put("title", "考试")
        typeMap5.put("data", "4")
        typeMap5.put("select", "false")
        typeList.add(typeMap5)
        val memoryMap: HashMap<String, String> = HashMap()
        memoryMap.put("title", "未记忆")
        memoryMap.put("data", "01")
        memoryMap.put("select", "false")
        memoryList.add(memoryMap)
        val memoryMap2: HashMap<String, String> = HashMap()
        memoryMap2.put("title", "开始记忆")
        memoryMap2.put("data", "02")
        memoryMap2.put("select", "false")
        memoryList.add(memoryMap2)
        val memoryMap3: HashMap<String, String> = HashMap()
        memoryMap3.put("title", "正在巩固")
        memoryMap3.put("data", "03")
        memoryMap3.put("select", "false")
        memoryList.add(memoryMap3)
        val memoryMap4: HashMap<String, String> = HashMap()
        memoryMap4.put("title", "已牢记")
        memoryMap4.put("data", "04")
        memoryMap4.put("select", "false")
        memoryList.add(memoryMap4)
        val memoryMap5: HashMap<String, String> = HashMap()
        memoryMap5.put("title", "开始遗忘")
        memoryMap5.put("data", "05")
        memoryMap5.put("select", "false")
        memoryList.add(memoryMap5)
        val memoryMap6: HashMap<String, String> = HashMap()
        memoryMap6.put("title", "已遗忘")
        memoryMap6.put("data", "06")
        memoryMap6.put("select", "false")
        memoryList.add(memoryMap6)
        subjectAdapter = TitleAdapter(R.layout.item_subject_choice, this, subjectList)
        rvSubject.setAdapter(subjectAdapter)
        typeAdapter = TitleAdapter(R.layout.item_subject_choice, this, typeList)
        rvType.setAdapter(typeAdapter)
        memoryAdapter = TitleAdapter(R.layout.item_subject_choice, this, memoryList)
        rvMemory.setAdapter(memoryAdapter)
        subjectAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (subjectList.get(position).get("select").equals("true")) {
                subjectList.get(position).put("select", "false")
                selectSubject.remove(subjectList.get(position).get("data"));
            } else {
                subjectList.get(position).put("select", "true")
                selectSubject.add(subjectList.get(position).get("data").toString())
            }
            var subjectTypeCode: String? = null
            for (i in 0 until selectSubject.size) {
                if (i == 0) {
                    subjectTypeCode = selectSubject.get(i)
                } else {
                    subjectTypeCode = subjectTypeCode + "," + selectSubject.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            viewModel.subjectTypeCode = subjectTypeCode.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex)
            rlType.visibility = View.GONE
            rvSubject.visibility = View.GONE
            if (selectSubject.size > 0) {
                ivSubjectShaixuan.setBackgroundResource(R.drawable.tx_sx_sel)
            } else {
                ivSubjectShaixuan.setBackgroundResource(R.drawable.tx_sx_unsel)
            }
        }
        typeAdapter!!.setOnItemClickListener { adapter, view, position ->
            var sourceType: String? = ""
            if (position == 0) {
                for (i in 0 until typeList.size) {
                    if (i == 0) {
                        typeList.get(0).put("select", "true")
                    } else {
                        typeList.get(i).put("select", "false")
                    }
                }
                selectType.clear()
            } else {
                if (typeList.get(0).get("select").equals("true")) {
                    typeList.get(0).put("select", "false")
                }
                if (typeList.get(position).get("select").equals("true")) {
                    typeList.get(position).put("select", "false")
                    selectType.remove(typeList.get(position).get("data"));
                } else {
                    typeList.get(position).put("select", "true")
                    selectType.add(typeList.get(position).get("data").toString())
                }
            }
            for (i in 0 until selectType.size) {
                if (i == 0) {
                    sourceType = selectType.get(i)
                } else {
                    sourceType = sourceType + "," + selectType.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            viewModel.sourceType = sourceType.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex)
            rlType.visibility = View.GONE
            rvSubject.visibility = View.GONE
            if (selectType.size > 0) {
                ivTypeShaixuan.setBackgroundResource(R.drawable.icon_ct_flei_sel)
            } else {
                ivTypeShaixuan.setBackgroundResource(R.drawable.icon_ct_flei)
            }
        }
        memoryAdapter!!.setOnItemClickListener { adapter, view, position ->
            if (memoryList.get(position).get("select").equals("true")) {
                memoryList.get(position).put("select", "false")
                selectMemory.remove(memoryList.get(position).get("data"));
            } else {
                memoryList.get(position).put("select", "true")
                selectMemory.add(memoryList.get(position).get("data").toString())
            }
            var memoryLvl: String? = null
            for (i in 0 until selectMemory.size) {
                if (i == 0) {
                    memoryLvl = selectMemory.get(i)
                } else {
                    memoryLvl = memoryLvl + "," + selectMemory.get(i)
                }
            }
            adapter.notifyDataSetChanged()
            viewModel.memoryLvl = memoryLvl.toString()
            subjectIndex = 0
            gotoSubject(subjectIndex)
            rlType.visibility = View.GONE
            rvMemory.visibility = View.GONE
            if (selectMemory.size > 0) {
                ivMemory.setBackgroundResource(R.drawable.icon_ywqx_sel)
            } else {
                ivMemory.setBackgroundResource(R.drawable.icon_ywqx_unsel)
            }
        }
    }

    var deleteSubjectCode: String? = ""
    private fun deleteErrorSubject() {
        if (Urls.antiShake.check()) {
            return
        }
        if (subjectView == null) {
            return
        }
        if (subjectView.subject != null) {
            var subject = subjectView.subject!!
            if (deleteSubjectCode == subject.subjectCode) {
                return
            }
            deleteSubjectCode = subject.subjectCode
            viewModel.deleteErrorSubject(subject).observe(this, {
                if (it.error != null) {
                    errorToast(it.error.message ?: "")
                } else {
                    successToast("已删除错题")
                    subjectAllNums--
                    tvTopBarLeft.text = "" + (subjectIndex + 1) + "/" + subjectAllNums
                    refreshSubject()
                }
            })
        }

    }


    override fun onShowSubjectsLoaded(isShowData: Boolean) {
        if (isShowData) {
            ivSubjectShaixuan.visibility = View.VISIBLE
            ivMemory.visibility = View.VISIBLE
            ivTypeShaixuan.visibility = View.VISIBLE
            llFloatBtns.visibility = View.VISIBLE
            subjectScrollView.visibility = View.VISIBLE
            topBar.visibility = View.VISIBLE
            ivNext.visibility = View.INVISIBLE
            llEmpty.visibility = View.GONE
            tvTopBarLeft.text = "" + (subjectIndex + 1) + "/" + viewModel.total
            if (beitiType) {
                if (subjectView.subject?.subjectTypeCode.equals("1004")) {
                    subjectView().updateMyAnswers(subjectView.subject?.optionLvlNo?.split("@#^"))
                } else if (subjectView.subject?.subjectTypeCode.equals("1005")) {
                    var value: ArrayList<String> = ArrayList()
                    value.add(subjectView.subject?.optionLvlNo.toString())
                    subjectView().updateMyAnswers(value)
                } else {
                    subjectView().updateMyAnswers(subjectView.subject?.optionLvlNo?.split(","))
                }
                submitMyAnswer(true)
            }
        } else {
            if (viewModel.subjectList.size > 0) {
                MyToast.show("已经是最后一题了")
//                subjectIndex = 0;
//                gotoSubject(subjectIndex)
            } else {
                llFloatBtns.visibility = View.INVISIBLE
                subjectScrollView.visibility = View.INVISIBLE
                topBar.visibility = View.INVISIBLE
                ivNext.visibility = View.INVISIBLE
                llEmpty.visibility = View.VISIBLE
                tvEmptyView1.text = "错题本是空的"
                tvEmptyView2.text = "快去题库参与答题吧"
            }
        }

    }
//    private fun getSameDayPracticeNum() {
//        viewModel.getSameDayPracticeNum().observe(this, {
//            if (it.error != null) {
//                errorToast(it.error.message ?: "")
//            } else if (it.data != null) {
//                if (!beitiType) {
//                    tvTopBarLeft.text = "今日练习: ${it.data.totalNum}题"
//                    tvTopBarRight.text =
//                        "正确率: ${ClearMoreZeroUtil.subZeroAndDot(it.data.rightRatio)}%"
//                }
//            }
//        })
//    }

    class TitleAdapter(
        layoutResId: Int,
        context: Context,
        data: java.util.ArrayList<HashMap<String, String>>
    ) : BaseQuickAdapter<HashMap<String, String>, BaseViewHolder>(layoutResId, data) {

        override fun convert(holder: BaseViewHolder, item: HashMap<String, String>) {
            val ivStatus = holder?.getView<ImageView>(R.id.ivStatus)
            val tvTiltle = holder?.getView<TextView>(R.id.tvTiltle)
            tvTiltle?.text = item?.get("title")
            if (item?.get("select").equals("true")) {
                tvTiltle?.isSelected = true
                ivStatus?.isSelected = true
            } else {
                tvTiltle?.isSelected = false
                ivStatus?.isSelected = false
            }
        }

    }

    override fun initData() {

    }
}